//
//  mainViewController.m
//  nonghubao
//
//  Created by 王 文彬 on 13-1-24.
//  Copyright (c) 2013年 mypocketbaby. All rights reserved.
//

/*
 说明
 
 本类是主体框架类，负责绘制一个有多个导航VC的TabBarVC。每个TabBarItem都是用一个图片来代表的，并且文字和图片是在一起的。同时TabBar的选中后背景被重新定义。
 
 》TabBar的选中背景被重新定义，TabBar的背景也被替换‘
 》各NavigationVC的TabBarItem，选中和不选中都为同一个图片，这个图片既有图，也有字。因此，这个图片使用了imageInsets来偏移，以保持在TabBar的范围内。
 同时，title也被使用titlePositionAdjustment偏移到界面之外，以免引起文字相互覆盖。
 》向服务器问是否要同步通讯录电话
*/

#import "MainViewController.h"
#import "DynamicViewController.h"
#import "NoticeViewController.h"
#import "MoreViewController.h"
#import "Config.h"
#import "Helper.h"
#import "BuyerSellerViewController.h"
#import <AddressBook/AddressBook.h>
#import "JSONRequest.h"
#import "MoonHTTPRequest.h"
#import "ProvincePickerViewController.h"

@interface MainViewController ()<JSONRequestDelegate>

@end

@implementation MainViewController
{
    BOOL   _didSyncPhoneBook;   //是否同步过电话薄了
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    
    
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    //动态部分
    UIImage* tabBarIconDynamic   = [UIImage imageNamed:@"com_btn_009"]; 
    _dynamicViewController = [[DynamicViewController alloc] initWithStyle:UITableViewStyleGrouped];
    [self tabBarItemSetting:_dynamicViewController withIcon:tabBarIconDynamic];
    
    UINavigationController* dynamicNavigationController = [[UINavigationController alloc] initWithRootViewController:_dynamicViewController];  //创建浏览视图
    [Helper navigationControllerCommonStyle:dynamicNavigationController];
    
    //消息通知部分
    UIImage* tabBarIconNotice    = [UIImage imageNamed:@"com_btn_010"];
    _noticeViewController = [[NoticeViewController alloc] initWithStyle:UITableViewStyleGrouped];
    [self tabBarItemSetting:_noticeViewController withIcon:tabBarIconNotice];

    UINavigationController* noticeNavigationController = [[UINavigationController alloc] initWithRootViewController:_noticeViewController];
    [Helper navigationControllerCommonStyle:noticeNavigationController];
    
    
    //我是买家
    UIImage* tabBarIconBuyer       = [UIImage imageNamed:@"com_btn_011"];
    _buyerViewController = [[BuyerSellerViewController alloc] initWithType:BusinessTypeBuyer];
    [self tabBarItemSetting:_buyerViewController withIcon:tabBarIconBuyer];
    
    UINavigationController* buyerNavigationController = [[UINavigationController alloc] initWithRootViewController:_buyerViewController];
    [Helper navigationControllerCommonStyle:buyerNavigationController];
    
    
    //我是卖家
    UIImage* tabBarIconStatistic = [UIImage imageNamed:@"com_btn_012"];
    _sellerViewController = [[BuyerSellerViewController alloc] initWithType:BusinessTypeSeller];
    [self tabBarItemSetting:_sellerViewController withIcon:tabBarIconStatistic];
    
    UINavigationController* sellerNavigationController = [[UINavigationController alloc] initWithRootViewController:_sellerViewController];
    [Helper navigationControllerCommonStyle:sellerNavigationController];
    
    
    //更多部分
    UIImage* tabBarIconMore      = [UIImage imageNamed:@"com_btn_013"];
    _moreViewController = [[MoreViewController alloc] init];
    [self tabBarItemSetting:_moreViewController withIcon:tabBarIconMore];
    
    UINavigationController* moreNavigationController = [[UINavigationController alloc] initWithRootViewController:_moreViewController];
    [Helper navigationControllerCommonStyle:moreNavigationController];
    
    
    //将创建好的NavigationVC们放入
    self.viewControllers = @[dynamicNavigationController, noticeNavigationController, buyerNavigationController, sellerNavigationController, moreNavigationController];
    self.tabBar.backgroundImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"com_bg_002@2x" ofType:@"png"]];    //改变TabBar的背景
    self.tabBar.selectionIndicatorImage = [UIImage imageNamed:@"com_bg_003"];     //改变选中某个TabBarItem后的背景图片
   
//    [self syncPhonebookCheckRequest];
    
    
    //此处为临时处理方式，应放在登录成功后
    if ([_CONFIG_APP_KEY isEqualToString:@"XYSHQ"]) {
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_U_GET_BASICINFO];
        request.delegate = self;
        [request setValue:_ACCOUNT_TOKEN forParameter:@"token"];
        [request setValue:_ACCOUNT_ID forParameter:@"userId"];
        [request setSuccessSelector:@selector(basicInfoDidReceived:)];
        [request asynchronous];
    }

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    [Helper syncPhoneBook];

    if (_didSyncPhoneBook == false) {   //只做一次，同时也是用于避免与MoreVC的客服冲突问题
        
        _didSyncPhoneBook = true;

        MoonHTTPRequest* moon = [[MoonHTTPRequest alloc] initWithURLString:_JSON_URL_U_SYNCPHONEBOOK_CHECK];
        [moon onSuccess:^(id result) {
//            NSLog(@"main....>%@", result);
            //零时补丁，解决在MoreVC中，客服界面退出时的崩溃。问题不详，待查
            if ([result[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                return;
            }
            
            if ([result[@"status"] intValue] == 1 && [result[@"data"] boolValue]) {
                
                [Helper syncPhoneBook];
            }
        }];
        [moon asynchronous];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)basicInfoDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    if (jmf.status == JMStatusSucceed) {

        if ( [_CONFIG_APP_KEY isEqualToString:@"XYSHQ"] && (jmf.data[@"school"] == [NSNull null] || [jmf.data[@"school"] isEqualToString:@""])) {
            
            //不是在校园生活圈注册，但又是第一次登录XYSHQ的，标记。
            //以便在选择后向服务器请求修改个人信息
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstTimeInXYSHQ"];
            
            UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_136") delegate:self cancelButtonTitle:_L(@"btn_yes_46") otherButtonTitles: nil];
            [alertView show];
        }
    }
}

// 请求失败
//
- (void)requestFailWithNetworkUnavailabe
{
}

#pragma mark - UIAlertView Delegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    ProvincePickerViewController *provincePickerVC = [[ProvincePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
    UINavigationController *provincePickerNC = [[UINavigationController alloc] initWithRootViewController:provincePickerVC];
    [Helper navigationControllerCommonStyle:provincePickerNC];
    
    UIWindow *window = [UIApplication sharedApplication].windows[0];
    UITabBarController *tabBarController = (UITabBarController *)window.rootViewController;
    
    UINavigationController *navController = (UINavigationController *)tabBarController.selectedViewController;
    
    [navController presentModalViewController:provincePickerNC animated:YES];
}

#pragma mark - 私有方法

// 用于为每个Tab制作背景，设定点击前后的图片
- (void)tabBarItemSetting:(UIViewController *)controller withIcon:(UIImage *)icon
{
    //由于给title赋值了，因此TabBar会显示这个title，最后会引起title与图片的文字重复，因此将文字偏移出视图之外
    controller.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, 15);
    
    //设置选中和非选中状态为同一个图片
    [controller.tabBarItem setFinishedSelectedImage:icon withFinishedUnselectedImage:icon];
    
    //由于设计的图片带文字，图片较大，必须偏移，否则图片顶部会超出bar
    controller.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);

}

@end
